<template>
  <div class="ai-chat-assistant">
    <!-- 聊天消息区域 -->
    <div ref="messageContainer" class="chat-messages">
      <div v-for="(message, index) in messages" :key="index" :class="['message', message.role]">
        <div :class="['bubble', message.role]">
          {{ message.content }}
        </div>
      </div>

      <!-- 加载指示器 -->
      <div v-if="isLoading" class="message bot">
        <div class="bubble bot">
          <span class="typing-dots"><span></span><span></span><span></span></span>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <el-input
        v-model="userInput"
        placeholder="您可以继续询问关于此病虫害的问题..."
        @keyup.enter="sendMessage"
        clearable
      >
        <template #append>
          <el-button :loading="isLoading" @click="sendMessage" icon="Promotion">发送</el-button>
        </template>
      </el-input>
    </div>
  </div>
</template>

<script>
import { startConversation, sendMessage } from "@/api/agroai";

export default {
  name: "AiChatAssistant",
  props: {
    // 初始消息内容
    initialMessage: {
      type: String,
      default: ""
    },
    // 是否自动发送初始消息
    autoSend: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      messages: [],
      userInput: '',
      isLoading: false,
      conversationId: null,
      hasAutoSent: false // 是否已自动发送
    };
  },
  watch: {
    // 监听autoSend变化，自动发送消息
    autoSend(newVal) {
      if (newVal && this.initialMessage && !this.hasAutoSent) {
        this.sendInitialMessage();
        this.hasAutoSent = true;
      }
    },
    // 监听initialMessage变化
    initialMessage(newVal) {
      // 如果消息变化且不为空，重置自动发送状态
      if (newVal && newVal.trim() !== "") {
        this.hasAutoSent = false;
      }
    }
  },
  mounted() {
    // 如果有初始消息，添加到消息列表但不立即发送
    if (this.initialMessage) {
      this.messages.push({ role: 'user', content: this.initialMessage });
    }
  },
  methods: {
    // 发送初始消息
    async sendInitialMessage() {
      this.isLoading = true;

      try {
        // 如果没有会话ID，则先创建会话
        if (!this.conversationId) {
          const startResp = await startConversation();
          this.conversationId = startResp.data;
        }

        // 发送初始消息
        const response = await sendMessage({
          conversationId: this.conversationId,
          message: this.initialMessage
        });

        const aiResponse = response.data;
        this.messages.push({ role: 'bot', content: aiResponse });

        // 通知父组件AI响应已收到
        this.$emit('ai-response-received');

      } catch (error) {
        console.error('调用AI接口失败:', error);
        this.messages.push({
          role: 'bot',
          content: '抱歉，获取病虫害信息时出现问题，请稍后再试。'
        });

        // 通知父组件AI响应失败
        this.$emit('ai-error', error);
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
    },

    // 发送用户输入的消息
    async sendMessage() {
      const message = this.userInput.trim();
      if (!message || this.isLoading) return;

      this.messages.push({ role: 'user', content: message });
      this.userInput = '';
      this.scrollToBottom();

      this.isLoading = true;

      try {
        // 如果没有会话ID，则先创建会话
        if (!this.conversationId) {
          const startResp = await startConversation();
          this.conversationId = startResp.data;
        }

        // 发送用户消息
        const response = await sendMessage({
          conversationId: this.conversationId,
          message: message
        });

        const aiResponse = response.data;
        this.messages.push({ role: 'bot', content: aiResponse });

      } catch (error) {
        console.error('调用AI接口失败:', error);
        this.messages.push({
          role: 'bot',
          content: '抱歉，我好像出了点问题，请再试一次。'
        });
      } finally {
        this.isLoading = false;
        this.scrollToBottom();
      }
    },

    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const container = this.$refs.messageContainer;
        if (container) {
          container.scrollTop = container.scrollHeight;
        }
      });
    }
  }
};
</script>

<style scoped>
.ai-chat-assistant {
  display: flex;
  flex-direction: column;
  height: 300px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  padding: 15px;
  overflow-y: auto;
  background-color: #fafafa;
}

.message {
  display: flex;
  margin-bottom: 12px;
}

.message.user {
  justify-content: flex-end;
}

.message.bot {
  justify-content: flex-start;
}

.bubble {
  max-width: 80%;
  padding: 10px 14px;
  border-radius: 18px;
  word-break: break-word;
  font-size: 14px;
}

.bubble.user {
  background-color: #1890ff;
  color: white;
  border-bottom-right-radius: 4px;
}

.bubble.bot {
  background-color: white;
  color: #333;
  border: 1px solid #ddd;
  border-bottom-left-radius: 4px;
}

.input-area {
  padding: 15px;
  border-top: 1px solid #e0e0e0;
  background-color: white;
}

/* 打字动画 */
.typing-dots {
  display: inline-flex;
  align-items: center;
}

.typing-dots span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background-color: #999;
  margin: 0 2px;
  animation: typingAnimation 1.4s infinite ease-in-out both;
}

.typing-dots span:nth-child(1) { animation-delay: -0.32s; }
.typing-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typingAnimation {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}
</style>
